package com.smt.repository.impl;

import com.smt.entity.Book;
import com.smt.repository.IBookRepository;
import org.elasticsearch.action.search.SearchType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Component;

import java.util.List;

import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.wildcardQuery;

/**
 * @autor xiaoyu.fang
 * @date 2019/6/13 11:24
 */
@Component
public class IBookRepositoryImpl implements IBookRepository<Book, String> {

    @Autowired
    private ElasticsearchTemplate esTemplate;

    @Override
    public List<Book> queryByBook(Book book) {
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        if (book.getName() != null) {
            // 通配符检索
            // nativeSearchQueryBuilder.withQuery(matchQuery("name", book.getName()));
            nativeSearchQueryBuilder.withSearchType(SearchType.QUERY_THEN_FETCH)
                    .withQuery(wildcardQuery("name", ("*" + book.getName() + "*").toLowerCase()));
        }
        if (book.getAuther() != null) {
            // 精确查询
            nativeSearchQueryBuilder.withQuery(termQuery("auther.keyword", book.getAuther()));
            // nativeSearchQueryBuilder.withFilter(matchQuery("auther", book.getAuther()));
        }
        SearchQuery searchQuery = nativeSearchQueryBuilder.build();
        return esTemplate.queryForList(searchQuery, Book.class);
    }

}
